
/**
 * Namespace    Classes.Service
 * Class        AddressService
 * Author       Bram Vandenbussche
 * Description  Provides business logic for an adress
 * Version      1.0
**/

var AddressService = new function() {
    var root = this;
	
	this.Addresses = null;
	this.SavedFileName = "addresses.xml";
    
    this.LoadAddresses = function() {
		this.Addresses = [];
        
        var xml = LoadXmlFromFile(this.SavedFileName);
        
        if (xml != undefined) {
			air.trace("AddressService: File found! Loading file xml");
            // if there is, load the settings from it
            this.LoadAddressesFromFile(xml);
        } else {
			air.trace("AddressService: File not found! Loading from WS");
            // if there isn't, create the default settings
            this.LoadAddressesFromWS(root.PersistAddresses);
        }
	}
	
	
	this.LoadAddressesFromFile = function(xml) {
		$.each($("address", xml), function() {
            var a = new Address();
            
            // Setting aanmaken vanuit xml
            a.Deserialize($(this));
            
            // Setting opslaan
            root.AddAddress(a);
        });
	}
	
	
	this.LoadAddressesFromWS = function(callback) {
		var getAddressesUrl = PrestashopService.PS_MOBILE_AUTHORIZATION.api.addresses["xlink:href"] + "?display=full";
		
		var getAddressesArgs = {
			url: getAddressesUrl,
			method: 'GET',
			dataType: "xml",
			async: false,
			beforeSend: function(jqXHR, settings) {            
				// Authentication
				PrestashopService.PrepareAjaxCredentials(jqXHR);
				
				// Status instellen
				SetStatus("loading");
			},
			success: function(data, textStatus, jqXHR) {
                air.trace("AddressService: WS response received");
            
				// Return data omvormen naar JSON
				var PS_MOBILE_ADDRESS_LIST = $.xml2json(data);
				
                air.trace("AddressService: parsed WS response");
                
				// Response data cachen
				root.AssembleFromJson(PS_MOBILE_ADDRESS_LIST.addresses.address);
                
                air.trace("AddressService: assembled WS response");
                
                if (callback != undefined)
                    callback();
			}
		}
		
		$.ajax(getAddressesArgs);
	}
	
	
	this.AssembleFromJson = function(sourceList) {
       if (sourceList.length == undefined) {
			var a = new Address();
				
			a.AssembleFromJson(sourceList);
			
			root.AddAddress(a);
		} else {
			for (var i in sourceList) {
                var a = new Address();
				
				a.AssembleFromJson(sourceList[i]);
				
				root.AddAddress(a);
			}
		}
    }
	
	this.PersistAddresses = function() {
		air.trace("AddressService: Persisting addresses to file");
        
        var xml = SerializeList(root.Addresses, "addresses");
        
        SaveXmlToFile(xml, root.SavedFileName);
	}
	
	
	this.AddAddress = function(a) {
		root.Addresses[a.ID] = a;
	}
	
	
	this.GetByID = function(id) {
		// Indien er nog geen klanten zijn opgehaald, dan doen we dat eerst
		if (this.Addresses == undefined) {
            this.LoadAddresses();
        }
		
		var foundAddress = null;
    
		// Eerst proberen we de klant te zoeken in de cache
		foundAddress = root.Addresses[id];
		
		// Als dat niet lukt, gaan we zoeken in de WS
		if (foundAddress == undefined) {
			var getAddressByIdUrl = PrestashopService.PS_MOBILE_AUTHORIZATION.api.addresses["xlink:href"] + "/" + id;
			
			var getAddressByIdArgs = {
				url: getAddressByIdUrl,
				method: 'GET',
				dataType: 'xml',
				async: false,
				beforeSend: function(jqXHR, settings) {            
					// Authentication
					PrestashopService.PrepareAjaxCredentials(jqXHR);
					
					// Status instellen
					SetStatus("loading");
				},
				success: function(data, textStatus, jqXHR) {
					foundAddress = new Address();
					
					foundAddress.AssembleFromJson($.xml2json(data).address);
                    
                    SetStatus("none");
				}
			}
		
			$.ajax(getAddressByIdArgs);
		}
		
		return foundAddress;
	}
	
	
	this.ClearAddresses = function() {
		root.Addresses = null;
	}
	
	this.ClearCache = function() {
		// Clear ordersfile
		DeleteFile(root.SavedFileName);
		
		// Clear orders in memory
		root.ClearAddresses();
		
		// Reload customers
		root.LoadAddresses();
	}
    
    this.GetAddressByCustomerID = function(customerId) {
        var foundAddress = null;
        
        for (var addressID in this.Addresses) {
            if (this.Addresses[addressID].CustomerID == customerId) {
                foundAddress = this.Addresses[addressID];
                break;
            }
        }
        
        return foundAddress;
    }
}